package com.eatme.core.search;

/**
 * 二分查找-非递归
 */
public class BinarySearchV2 {
    private BinarySearchV2() {

    }

    /**
     * 非递归二分查找法
     * @param data
     * @param target
     * @return
     * @param <E>
     */
    public static <E extends Comparable<E>> int search(E[] data,E target) {
        int l = 0, r = data.length -1;
        while (l<=r) {
            // 在 data[l,r] 的范围查找 target
            int mid = l + (r-l) /2 ; // 避免整型溢出
            if (data[mid].compareTo(target)==0)
                return mid;
            if (data[mid].compareTo(target)<0)
                l=mid+1;
            else r = mid-1;
        }
        return -1;
    }

    public static void main(String[] args) {
        Integer [] nums = {-1,0,3,5,9,12};
        Integer target = 9;
        int ret =BinarySearchV2.search(nums,target);
        System.out.println(ret);
    }
}
